//
//  AttestationViewControlller.swift
//  ShareCar
//
//  Created by 久众科技 on 2018/6/29.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import Foundation
import AipOcrSdk
import IDLFaceSDK


class AttestationViewControlller: UIViewController {
    
    @IBOutlet weak var nameTextField: UITextField!
    @IBOutlet weak var identifierTextField: UITextField!
    @IBOutlet weak var numberTextField: UITextField!
    
    var index = 10000  //标记当前点击的索引值
    var image : UIImage?
    var faceImageNameStr : String?
    var idcard_front_img : String?               //身份证正面照片（照片）
    var idcard_back_img : String?               //身份证背面照片（国徽）
    var idcard_hand_img : String?               //手持身份证照片
    var driving_license_img : String?           //驾驶证照片
    var driving_license_page_img : String?      //驾驶证副页照片
    
    var identString: String!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //默认的识别功能的回调
        showFaceViewController()
    }
    
    func showFaceViewController() {
        
        let vc = LivenessViewController()
        vc.delegate = self
        let model = LivingConfigModel.sharedInstance()!
        model.numOfLiveness = 1
        vc.livenesswithList(model.liveActionArray as! [Any]?, order: model.isByOrder, numberOfLiveness: model.numOfLiveness, and: self,andType: 0)
        present(vc, animated: true, completion: nil)
    }
    
    override var prefersStatusBarHidden: Bool {
        get {
            return false
        }
    }
    
    @IBAction func selectedImage(_ sender: UITapGestureRecognizer) {
        
        if faceImageNameStr == nil {
            showFaceViewController()
            return
        }
        
        index = sender.view!.tag
        switch sender.view?.tag {
        case 100: idcardOCROnlineFront()
        case 101: idcardOCROnlineBack()
        case 102: personAndImage()
        case 103: webImageOCR()
        case 104: webImageOCR()
        default: break
        }
    }
    //手持身份证
    func personAndImage() {
        
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            let  cameraPicker = UIImagePickerController()
            cameraPicker.delegate = self
            cameraPicker.allowsEditing = true
            cameraPicker.sourceType = .camera
            //在需要的地方present出来
            present(cameraPicker, animated: true, completion: nil)
        } else {
            showError("不支持拍照")
        }
        
    }
    
    //身份证正面照
    func idcardOCROnlineFront() -> Void {
        let vc = AipCaptureCardVC.viewController(with: .localIdCardFont) { [weak self] image in
            self?.afterImage(image: image)
            //识别图片
            AipOcrService.shard().detectIdCardFront(from: image, withOptions: nil, successHandler: { result in
                self?.getImageInfo(a: result as Any)
            }, failHandler: { (error) in
                XHProgressHUD.showError("图片识别失败，请重新上传!")
            })
        }
        
        present(vc!, animated: true, completion: nil)
    }
    
    //身份证反面
    func idcardOCROnlineBack() {
        let vc = AipCaptureCardVC.viewController(with: .localIdCardBack) { [weak self] image in
            self?.afterImage(image: image)
        }
        
        present(vc!, animated: true, completion: nil)
    }
    
    //网络图片
    func webImageOCR() {
        let vc = AipGeneralVC.viewController { [weak self] image in
            self?.afterImage(image: image)
            if let self = self ,self.index == 103 {
                
                JZLoading.showLoadingWith(toView: self.view)
                AipOcrService.shard()?.detectDrivingLicense(from: image, withOptions: nil, successHandler: { [weak self] result in
                    
                    DispatchQueue.main.async {
                        JZLoading.hideLoading()

                    }
                    let a = (((result as AnyObject)["words_result"] as? [String : Any])!["证号"] as AnyObject)["words"]
                    if let b = a {
                        if let c = b as? String {
                            print("读取身份证号:",c)
                            self?.identString = c
                        }
                        
                    }

                }, failHandler: { error in
                    
                    XHProgressHUD.showError("图片识别失败，请重新上传!")
                })
            }
        }
        
        present(vc!, animated: true, completion: nil)
    }
    
    //图片分析成功
    func getImageInfo(a:Any) {
        
        DispatchQueue.main.async {
            if self.index == 100 {
                //需要提取姓名,身份证号
                let some = (((a as AnyObject)["words_result"] as? [String : Any])!["姓名"] as AnyObject)["words"]
                let ID = (((a as AnyObject)["words_result"] as? [String : Any])!["公民身份号码"] as AnyObject)["words"]
                self.nameTextField.text = some as? String
                self.identifierTextField.text = ID as? String
            }
        }
    }
    
    //上传图片到服务器
    func uploadImage(image:UIImage?) {
        guard let img = image else {
            XHProgressHUD.showError("图片为空")
            return
        }
        
        //上传图片
        User.uploadFile(img) { [weak self] imagePath in
            switch self?.index {
            case 100:   self?.idcard_front_img = imagePath
            case 101:   self?.idcard_back_img = imagePath
            case 102:   self?.idcard_hand_img = imagePath
            case 103:   self?.driving_license_img = imagePath
            case 104:   self?.driving_license_page_img = imagePath
            case 10000: self?.faceImageNameStr = imagePath
            default:    self?.idcard_front_img = imagePath
            }
        }
    }
        
    func afterImage(image: UIImage?) {
        guard let image = image else {
            return
        }
        
        self.image = image
        //选取的图片赋值
        let imageView = self.view!.viewWithTag(self.index) as! UIImageView
        imageView.image = self.image
        self.dismiss(animated: true, completion: nil)
        //上传图片
        self.uploadImage(image: self.image)
    }
    
    @IBAction func authenticationuserInfo(_ sender: UIButton) {
        
        if self.faceImageNameStr  == nil {
            self.showError("请上传人脸识别照")
            return
        }
        
        if self.idcard_front_img  == nil {
            self.showError("请您上传身份证正面照片(1000)")
            return
        }
        
        if self.idcard_back_img == nil {
            self.showError("请您上传身份证反面照片(1001)")
            return
        }
        
        if self.idcard_hand_img == nil {
            self.showError("请您上传手持身份证照片(1002)")
            return
        }
        
        if self.driving_license_img == nil {
            self.showError("请您上传驾驶证正面照片(1007)")
            return
        }
        
        if self.driving_license_page_img == nil {
            self.showError("请您上传驾驶证副页照片(1008)")
            return
        }
        
        if (self.nameTextField.text?.isEmpty)! {
            self.showError("请您正确填写证件姓名(1005)")
            return
        }
        
        if (self.identifierTextField.text?.isEmpty)! {
            self.showError("请您正确填写证件号码(1006)")
            return
        }
        
        if (self.numberTextField.text?.isEmpty)! {
            self.showError("请填写驾驶证档案编号(1009)")
            return
        }
        
        if (self.numberTextField.text?.count != 12) {
            self.showError("请输入正确档案编号(1009)")
            return
        }
        
        guard let identValue = self.identifierTextField.text, identValue == self.identString else {
            showError("请确认身份证和驾驶证中身份证号一致；如一致将两张照片重新上传(1010)")
            return
        }
        
//        XHProgressHUD.showStatusInfo("正在识别认证中")
//        User.AuthenticationUserInfo(idcardFrontImg: self.idcard_front_img!,
//                                    idcardackImg: self.idcard_back_img!,
//                                    idcard_hand_img: self.idcard_hand_img!,
//                                    real_name: self.nameTextField.text!,
//                                    idcard_number: self.identifierTextField.text!,
//                                    driving_license_img: self.driving_license_img!,
//                                    driving_license_page_img: self.driving_license_page_img!,
//                                    driving_license_fn:self.numberTextField.text!,
//                                    face_img:self.faceImageNameStr!,
//                                    success: {
//                                        XHProgressHUD.dismiss()
//                                        if let user = User.info() {
//                                            XHProgressHUD.showSuccess("实名认证成功")
//                                            
//                                            user.certFlag = 2
//                                            user.username = self.nameTextField.text!
//                                            
//                                            User.saveUserInfo(user)
//                                            
//                                            self.slipViewController?.menuViewController?.refresh()
//
//                                            self.navigationController?.popToRootViewController(animated: true)
//                                        }
//        }) { error in
//            XHProgressHUD.dismiss()
//            self.showError(error)
//        }
    }
}

//#MARK: -- delegate

extension AttestationViewControlller: FaceDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func send(_ image: UIImage!) {
        DispatchQueue.main.async {
            self.uploadImage(image: image)
        }
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let image:UIImage = info[UIImagePickerControllerEditedImage] as! UIImage
        
        if let imageView = self.view.viewWithTag(self.index) as? UIImageView {
            imageView.image = image
            self.image = image
            //上传图片
            self.uploadImage(image: self.image)
            
        }
        
        self.dismiss(animated: true, completion: nil)
    }
}
